package poketrade;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import poketrade.entities.User;

/**
 * Servlet Filter implementation class AuthenticatedFilter
 * 
 * Ajoute un attribut user correspondant à l'utilisateur courant (soit null si il n'est pas logué).
 * Dans le cas de certaines requêtes nécessitant un blocage complet de la page si l'utilisateur
 * si il n'est pas connecté ou admin, la méthode shouldBlockUser devrait retourner true.
 */
public class AuthenticatedFilter implements Filter {

    /**
     * Default constructor. 
     */
    public AuthenticatedFilter() {
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}
	
	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

	       HttpSession session = ((HttpServletRequest)request).getSession(false);
	       User currentUser;
	       if (session != null)
	    	   currentUser = (User)session.getAttribute("user");
	       else
	    	   currentUser = null;
	       
	       String url = ((HttpServletRequest)request).getRequestURI();
	       
	       if (shouldBlockUser(currentUser, url))
	       {
	    	   ((HttpServletResponse) response).sendRedirect("NewsServlet");
	    	   return;
	       }
	       else
	       {
	    	   request.setAttribute("user", currentUser);
               chain.doFilter(request,response);
	       }
	}
	
	private boolean shouldBlockUser(User currentUser, String url)
	{
		if (currentUser == null)
		{
			if (url.equals("/Poketrade/profil.jsp")||(url.equals("Poketrade/posterAnnonce.jsp"))||(url.equals("Poketrade/posterNews.jsp"))||(url.equals("Poketrade/mesAnnonces.jsp"))||(url.equals("Poketrade/acheterCredit.jsp")))
				return true;
			else 
				return false;
		}
		else if ((currentUser.getAdmin()) && url.equals("Poketrade/posterNews.jsp"))
			return true;
		else 
			return false;
		

	}
}
